
package com.shop.cloud.upms.admin.service.impl;

import cn.hutool.core.util.IdUtil;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.shop.cloud.common.core.constant.CommonConstants;
import com.shop.cloud.common.data.tenant.TenantContextHolder;
import com.shop.cloud.mall.common.constant.MallConstants;
import com.shop.cloud.upms.admin.service.SysTenantService;
import com.shop.cloud.upms.common.entity.SysTenant;
import com.shop.cloud.upms.common.entity.SysTenantApply;
import com.shop.cloud.upms.admin.mapper.SysTenantApplyMapper;
import com.shop.cloud.upms.admin.service.SysTenantApplyService;
import lombok.AllArgsConstructor;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;

/**
 * 租户入驻申请表
 *
 * @author
 * @date 2023-12-12 14:47:16
 */
@Service
@AllArgsConstructor
public class SysTenantApplyServiceImpl extends ServiceImpl<SysTenantApplyMapper, SysTenantApply> implements SysTenantApplyService {

    private final SysTenantService sysTenantService;

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean verify(SysTenantApply sysTenantApply) {
        String status = sysTenantApply.getStatus();
        String applyDetail = sysTenantApply.getApplyDetail();
        sysTenantApply = baseMapper.selectById(sysTenantApply.getId());
        if(MallConstants.SHOPAPPLY_STATUS_0.equals(sysTenantApply.getStatus())) {//只有审核中状态的数据能操作
            sysTenantApply.setStatus(status);
            sysTenantApply.setApplyDetail(applyDetail);
            if(MallConstants.SHOPAPPLY_STATUS_1.equals(status)) {//如果审核通过，则需要添加租户和租户管理员
                SysTenant sysTenant = new SysTenant();
                String id = String.valueOf(IdUtil.getSnowflake(1,2).nextId());
                TenantContextHolder.setTenantId(id);
                sysTenantApply.setTenantId(id);
                sysTenant.setId(id);
                sysTenant.setName(sysTenantApply.getName());
                sysTenant.setCode(id);
                sysTenant.setExpireTime(LocalDateTime.now());
                sysTenant.setStatus(CommonConstants.STATUS_NORMAL);
                sysTenant.setPhone(sysTenantApply.getUserPhone());
                sysTenant.setUsername(sysTenantApply.getUserUsername());
                sysTenant.setPassword(sysTenantApply.getUserPassword());
                sysTenant.setUserPhone(sysTenantApply.getUserPhone());
                sysTenant.setCompanyCode(sysTenantApply.getCompanyCode());
                sysTenant.setCompanyName(sysTenantApply.getCompanyName());
                sysTenant.setCompanyLicense(sysTenantApply.getCompanyLicense());
                sysTenantService.save(sysTenant);
            }
            baseMapper.updateById(sysTenantApply);
        }
        return Boolean.TRUE;
    }
}
